<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

try {
    // 获取并验证输入数据
    $input = json_decode(file_get_contents('php://input'), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("无效的JSON格式");
    }
    // 参数校验
    $required = ['user_id', 'coach_id', 'rating'];
    foreach ($required as $field) {
        if (!isset($input[$field])) {
            throw new Exception("缺少必要参数: $field");
        }
    }
    $userId = filter_var($input['user_id'], FILTER_VALIDATE_INT);
    $coachId = filter_var($input['coach_id'], FILTER_VALIDATE_INT);
    $rating = filter_var($input['rating'], FILTER_VALIDATE_INT, [
        'options' => ['min_range' => 1, 'max_range' => 5]
    ]);
    $content = isset($input['content']) ? 
               mb_substr(trim($input['content']), 0, 200) : '';

    if (!$userId || !$coachId || !$rating) {
        throw new Exception("参数验证失败");
    }
    // 开启事务
    $conn->begin_transaction();
    try {
        // 插入评价记录
        $insertStmt = $conn->prepare("
            INSERT INTO coach_evaluate 
            (user_id, coach_id, rating, content, status) 
            VALUES (?, ?, ?, ?, 0)  -- 0表示待审核
        ");
        $insertStmt->bind_param("iiis", $userId, $coachId, $rating, $content);
        
        if (!$insertStmt->execute()) {
            throw new Exception("评价提交失败: " . $insertStmt->error);
        }
        // 计算最新平均分
        $updateStmt = $conn->prepare("
            UPDATE coaches 
            SET rating = (
                SELECT ROUND(AVG(rating), 1) 
                FROM coach_evaluate 
                WHERE coach_id = ? 
                  AND status = 1  -- 仅统计已通过审核的评价
            )
            WHERE id = ?
        ");
        $updateStmt->bind_param("ii", $coachId, $coachId);
        if (!$updateStmt->execute()) {
            throw new Exception("评分更新失败: " . $updateStmt->error);
        }
        // 提交事务
        $conn->commit();
        echo json_encode([
            'status' => 'success',
            'msg' => '评价已提交，审核通过后会显示'
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    error_log("Submit Evaluate Error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'msg' => $e->getMessage()
    ]);
} finally {
    if (isset($insertStmt)) $insertStmt->close();
    if (isset($updateStmt)) $updateStmt->close();
    $conn->close();
}
?>

